package com.example.homework.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.homework.db.models.Episode
import com.example.homework.db.apis.RetrofitService
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

class EpisodeViewModel : ViewModel() {
    private val _episodesStateFlow: MutableStateFlow<List<Episode>> =
        MutableStateFlow<List<Episode>>(listOf())
    val episodesFlow: Flow<List<Episode>> = _episodesStateFlow.asStateFlow()

    init {
        loadData()
    }

    fun loadData(page: Int = 0) {
        viewModelScope.launch {
            _episodesStateFlow.value = RetrofitService.episodesApi.getAll(page).result
        }
    }
    fun getOne(id: Int): Episode {
        val result: Deferred<Episode> = viewModelScope.async {
            RetrofitService.episodesApi.getOne(id)
        }
        return runBlocking { result.await() }
    }
}